package com.sch.study.http;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;

import java.io.IOException;
import java.util.Random;

public class HttpClientUtils {
    private static final Log log = LogFactory.getLog(HttpClientUtils.class);
    private static ThreadSafeClientConnManager cm = null;
    static {
        SchemeRegistry schemeRegistry = new SchemeRegistry();
        schemeRegistry.register(new Scheme("http", 80, PlainSocketFactory
                .getSocketFactory()));

        cm = new ThreadSafeClientConnManager(schemeRegistry);
        try {
            int maxTotal = 100;
            cm.setMaxTotal(maxTotal);
        } catch (NumberFormatException e) {
            log.error(
                    "Key[httpclient.max_total] Not Found in systemConfig.properties",
                    e);
        }
        // 每条通道的并发连接数设置（连接池）
        try {
            int defaultMaxConnection = 50;
            cm.setDefaultMaxPerRoute(defaultMaxConnection);
        } catch (NumberFormatException e) {
            log.error(
                    "Key[httpclient.default_max_connection] Not Found in systemConfig.properties",
                    e);
        }
    }

    public static HttpClient getHttpClient() {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
                HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 3000); // 3000ms
        return new DefaultHttpClient(cm, params);
    }

    public static void release() {
        if (cm != null) {
            cm.shutdown();
        }
    }

    public static void main(String[] args) throws ClientProtocolException,
            IOException {
//        String city = "北京";
//        String address="北京市海淀区彩和坊路海淀西大街74号";
////        URLEncoder.encode(value, "UTF-8")
//        HttpClient client = getHttpClient();
//        try {
//            HttpPost httpost = new HttpPost("http://apis.map.qq.com/ws/geocoder/v1");
//            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
////提交两个参数及值
//            nvps.add(new BasicNameValuePair("region", URLEncoder.encode(city, "UTF-8")));
//            nvps.add(new BasicNameValuePair("address",URLEncoder.encode(address, "UTF-8")));
//            nvps.add(new BasicNameValuePair("key","TJ3BZ-2VN3D-6LW4P-P2V2R-J3SLK-OOFSS"));
////设置表单提交编码为UTF-8
//            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
//            HttpResponse response = client.execute(httpost);
//            HttpEntity entity = response.getEntity();
//            System.out.println("Login form get: " + response.getStatusLine());
//            EntityUtils.consume(entity);
//        } finally {
//// When HttpClient instance is no longer needed,
//// shut down the connection manager to ensure
//// immediate deallocation of all system resources
//            client.getConnectionManager().shutdown();
//        }
        Random r = new Random();
        for (int i = 0; i < 10; i++) {
            long l1 = System.currentTimeMillis();
            HttpClient client = getHttpClient();


            /*
            http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1

             */
            HttpGet get = new HttpGet("http://apis.map.qq.com/ws/geocoder/v1/?location=39.984154,116.307490&key=OB4BZ-D4W3U-B7VVO-4PJWW-6TKDJ-WPB77&get_poi=1");

            HttpResponse response = client.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                long l = entity.getContentLength();
                System.out.println("回应结果长度:" + l);
            }
            System.out.println("查询耗时" + (System.currentTimeMillis() - l1));
        }
    }

}
